import featcher from 'fermionjs/lib/fetch';
import cookie from 'react-cookies';

function FetchResponseJsonParseError(response) {
	let message;
	if (typeof response === 'object') {
		message = response.message || response.msg || 'FetchResponseJsonParseError';
	} else {
		message = response;
	}
	return {
		message,
		name: 'FetchResponseJsonParseError',
		response,
		stack: new Error().stack,
	};
}
function FetchResponseError({ status, statusText, response }) {
	let message;
	if (typeof response === 'object') {
		message = response.message || response.msg || 'FetchResponseError';
	} else {
		message = response;
	}
	return {
		message,
		name: 'FetchResponseError',
		status,
		statusText,
		response,
		stack: new Error().stack,
	};
}

function Fetch(u, option = {}) {
	const { checkStatus } = option;
	return featcher(u, {
		...option,
		checkStatus: async resp => {
			const { status, statusText } = resp;
			if (status === 401) {
				const cookieSetup = {
					path: '/',
					domain: window.location.hostname.includes('console.')
						? '.scanv.com'
						: window.location.hostname,
				};
				cookie.save('token', '', cookieSetup);
				window.location.href =
					'/api/v2/users/login?service=' + window.location.origin + '/';
			}
			if (
				(checkStatus && status === checkStatus) ||
				(status >= 200 && status < 300)
			) {
				return Promise.resolve(resp);
			}
			let respContent;
			try {
				respContent = await parseJSON(resp);
			} catch (error) {
				respContent = error.response;
			}
			throw FetchResponseError({ status, statusText, response: respContent });
		},
	});
}
async function parseJSON(resp) {
	const text = await resp.text();
	try {
		return JSON.parse(text);
	} catch (error) {
		throw new FetchResponseJsonParseError(text);
	}
}

export default Fetch;
